<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix header-container">
        <div class="header-title">
          <el-icon><Management /></el-icon>
          <span>在售商品</span>
        </div>
        <div class="header-controls">
          <el-input
              placeholder="---请输入商品编号---"
              v-model="searchKeyword"
              class="input-with-select"
              clearable
          >
            <template #append>
              <el-button type="primary" @click="submitSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-select v-model="selectedFilter" placeholder="筛选" class="filter-select" @change="handleSearch">
            <el-option label="全部" value="all"></el-option>
            <el-option label="书籍" value="书籍"></el-option>
            <el-option label="电子设备" value="电子设备"></el-option>
            <el-option label="学习用品" value="学习用品"></el-option>
            <el-option label="服装" value="服装"></el-option>
            <el-option label="体育用品" value="体育用品"></el-option>
            <el-option label="个人护理用品" value="个人护理用品"></el-option>
            <el-option label="日常装饰品" value="日常装饰品"></el-option>
            <el-option label="乐器" value="乐器"></el-option>
          </el-select>
        </div>
      </div>
      <el-table :data="filteredData" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="product_id" label="商品编号" width="180"></el-table-column>
        <el-table-column prop="product_name" label="商品名称" width="180"></el-table-column>
        <el-table-column prop="product_price" label="商品单价">
          <template #default="scope">
            <span>{{ scope.row.product_price }}</span><span class="red-text"> 元</span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="商品类别"></el-table-column>
        <el-table-column prop="product_detail" label="商品详情"></el-table-column>
        <el-table-column label="商品图片">
          <template #default="scope">
            <el-image
                :src="`/${scope.row.product_image}`"
                class="product-image"
                fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>

  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 4, 5, 6]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total+1"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<script>
import axios from 'axios';
import { Search, Management } from '@element-plus/icons-vue';

export default {
  components: {
    Search,
    Management
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      pageInfo: {},
      searchKeyword: '',
      selectedFilter: 'all',
      tableData: [],
      filteredData: [],
      currentAdminName: '' // Define currentAdminName
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('http://localhost:8080/approvalproduct/product')
          .then(response => {
            this.tableData = response.data;
            this.filteredData = response.data;
            this.LoadStuPageData(); // Call LoadStuPageData after data is fetched
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
    },
    handleSearch() {
      let filtered = this.tableData;
      if (this.selectedFilter && this.selectedFilter !== 'all') {
        filtered = filtered.filter(item => item.category === this.selectedFilter);
      }
      if (this.searchKeyword) {
        filtered = filtered.filter(item => item.product_id.toString().includes(this.searchKeyword));
      }
      this.filteredData = filtered;
    },
    submitSearch() {
      this.handleSearch();
      // Clear searchKeyword after search
      this.searchKeyword = '';
    },
    handleDelete(Del) {
      this.$confirm('确定下架该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8080/approvalproduct/updatestatus', {
          product_id: Del.product_id,
          operator: this.currentAdminName
        }).then(response => {
          if (response.data === 1) {
            this.$message({
              type: 'success',
              message: '商品下架成功!'
            });
            this.fetchData();
          } else {
            this.$message.error('商品下架失败，请重试！');
          }
        }).catch(error => {
          console.error('Error updating product status:', error);
          this.$message.error('商品下架失败，请重试！');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },

    LoadStuPageData() {
      axios.get("http://localhost:8080/approvalproduct/pages", {
        params: {
          page: this.currentPage,
          size: this.pageSize
        }
      }).then((res) => {
        this.pageInfo = res.data;
      }).catch((err) => {
        console.log(err);
      });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.LoadStuPageData();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.LoadStuPageData();
    }
  },
  mounted() {
    this.currentAdminName = localStorage.getItem('adminName');
  }
};
</script>

<style scoped>
.box-card {
  width: 95%;
  margin: 20px auto;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title el-icon {
  margin-right: 5px;
}

.header-controls {
  display: flex;
  align-items: center;
}

.input-with-select .el-input-group__append {
  background-color
  : #409eff;
  color: white;
}

.filter-select {
  width: 50%;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.red-text {
  color: red;
}
</style>
